package com.atguigu.srb.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.srb.oss.config.OssProperties;
import com.atguigu.srb.oss.service.ApiOssService;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Service
public class ApiOssServiceImpl implements ApiOssService {

    @Override
    public String upload(String module, MultipartFile multipartFile) {
        //Url = 桶名+”.”+节点(endpoint)+”/”+module+”/” + 日期 + “/” + uuid + “文件名” + 文件后缀
        OSS oss = new OSSClientBuilder().build(OssProperties.ENDPOINT, OssProperties.KEY_ID, OssProperties.KEY_SECRET);
        String dateTime = new DateTime().toString("yyyy/MM/dd");
        String originalFilename = multipartFile.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
        String uuid = UUID.randomUUID().toString();
        try {
            oss.putObject(OssProperties.BUCKET_NAME,module+"/"+dateTime+"/"+uuid+"."+filenameExtension,multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        oss.shutdown();
        String url = "https://"+OssProperties.BUCKET_NAME+"."+OssProperties.ENDPOINT+"/"+module+"/"+dateTime+"/"+uuid+"."+filenameExtension;
        return url;
    }

    @Override
    public boolean remove(String url) {
        OSS oss = new OSSClientBuilder().build(OssProperties.ENDPOINT, OssProperties.KEY_ID, OssProperties.KEY_SECRET);
        String storeUrl = url.substring(("https://"+OssProperties.BUCKET_NAME+"."+OssProperties.ENDPOINT+"/").length());
        oss.deleteObject(OssProperties.BUCKET_NAME,storeUrl);
        oss.shutdown();
        return true;
    }
}
